package com.chongyuan.producer.web.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.quickserver.net.server.ClientHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chongyuan.producer.common.DeviceInfo;
import com.chongyuan.producer.common.RedisConstant;
import com.chongyuan.producer.util.RedisUtil;
import com.icafebutler.framework.util.StringUtil;
import com.icafebutler.framework.web.BaseController;

/**
 * 
 * 
 * @author taof.feng
 * @version $Id: ChangeDeviceRateController.java, v 0.1 2018年4月18日 下午3:47:47
 *          taof.feng Exp $
 */
@Controller
@RequestMapping("/changeRate")
public class ChangeDeviceRateController extends BaseController {

	@RequestMapping(value = "/changeDeviceRate")
	@ResponseBody
	public String changeDeviceRate(HttpServletRequest request, HttpServletResponse response, String deviceId, boolean isStart) {
		// 删除上次遛狗的点
		RedisUtil.delkeyObject(RedisConstant.DEVICE_GPS_MSG_LIST + deviceId);
		String uploadReply = "";
		if (isStart) {
			uploadReply = "[CY*" + deviceId + "*0001*" + "0009*UPLOAD" + ",10]";
			RedisUtil.setObject(RedisConstant.DEVICE_DOG_IS_RUN + deviceId, "true", 60 * 60 * 24);
		} else {
			uploadReply = "[CY*" + deviceId + "*0001*" + "000b*UPLOAD" + ",1800]";
			RedisUtil.setObject(RedisConstant.DEVICE_DOG_IS_RUN + deviceId, "false", 60 * 60 * 2);
		}

		DeviceInfo deviceInfo = (DeviceInfo) RedisConstant.socektMap.get(RedisConstant.DEVICE_SOCKET_CLIENT + deviceId);
		try {
			if (deviceInfo != null) {
				ClientHandler handler = deviceInfo.getHandler();
				if (handler == null) {
					return "error";
				}
				deviceInfo.setIsRuning(isStart);
				if (isStart) {
					deviceInfo.setStartTime(new Date());
				}
				handler.sendClientMsg(uploadReply);
				RedisConstant.socektMap.put(RedisConstant.DEVICE_SOCKET_CLIENT + deviceId, deviceInfo);
				System.out.println("发送指令：" + uploadReply);
			} else {
				return "error";
			}
		} catch (Exception e) {
			return "error";
		}
		return "success";
	}

	@RequestMapping(value = "/setFamilyNumber")
	@ResponseBody
	public String setFamilyNumber(HttpServletRequest request, HttpServletResponse response, String deviceId, String phones) {
		if (StringUtil.isBlank(phones) || StringUtil.isBlank(deviceId)) {
			return "error";
		}
		String[] phoneArray = phones.split(",");
		if (phoneArray.length < 1) {
			return "error";
		}
		StringBuffer sb = new StringBuffer();
		String uploadReply = "";
		int len = 1;
		sb.append("[CY*").append(deviceId).append("*0001*");
		StringBuffer phoneSb = new StringBuffer();
		phoneSb.append("PHB,1234,").append(phoneArray.length).append(",");
		for (int i = 0; i < phoneArray.length; i++) {
			if (i + 1 == phoneArray.length) {
				phoneSb.append(i + 1).append("-").append(phoneArray[i]).append("-").append(phoneArray[i]);
			} else {
				phoneSb.append(i + 1).append("-").append(phoneArray[i]).append("-").append(phoneArray[i]).append("|");
			}
		}

		len = phoneSb.length();
		sb.append(change(len + "", 10, 16)).append("*").append(phoneSb).append("]");
		uploadReply = sb.toString();
		ClientHandler handler = (ClientHandler) RedisConstant.socektMap.get(RedisConstant.DEVICE_SOCKET_CLIENT + deviceId);
		try {
			if (handler != null) {
				handler.sendClientMsg(uploadReply);
				System.out.println("发送亲情号指令：" + uploadReply);
			} else {
				return "error";
			}
		} catch (Exception e) {
			return "error";
		}
		return "success";
	}

	@RequestMapping(value = "/positioning")
	@ResponseBody
	public String positioning(HttpServletRequest request, HttpServletResponse response, String deviceId) {
		String uploadReply = "[CY*" + deviceId + "*0001*" + "0002*" + "CR]";

		ClientHandler handler = (ClientHandler) RedisConstant.socektMap.get(RedisConstant.DEVICE_SOCKET_CLIENT + deviceId);
		try {
			if (handler != null) {
				handler.sendClientMsg(uploadReply);
				System.out.println("发送指令：" + uploadReply);
			} else {
				System.out.println("未获取到设备连接信息，设备id：" + deviceId);
				return "error";
			}
		} catch (Exception e) {
			return "error";
		}
		return "success";
	}

	/**
	 * 任意转换
	 * 
	 * @param num
	 *            需要转换的数值
	 * @param from
	 *            现在的进制
	 * @param to
	 *            要转的进制
	 * @return
	 */
	private static String change(String num, int from, int to) {
		String result = new java.math.BigInteger(num, from).toString(to);

		if (result.length() < 4) {
			int zeroCnt = 4 - result.length();
			for (int i = 0; i < zeroCnt; i++) {
				result = "0" + result;
			}
		}

		return result;
	}

	public static void main(String[] args) {
		String string = "INIT,13256122653,0,k6_BASE_V1.00_2016_03,0001,0001";
		System.out.println(string.length());

		String deviceId = "014111001349678";
		String phones = "15715767385,13857169791";

		String[] phoneArray = phones.split(",");
		StringBuffer sb = new StringBuffer();
		String uploadReply = "";
		int len = 1;
		sb.append("[CY*").append(deviceId).append("*0001*");
		StringBuffer phoneSb = new StringBuffer();
		phoneSb.append("PHB,1234,").append(phoneArray.length).append(",");
		for (int i = 0; i < phoneArray.length; i++) {
			if (i + 1 == phoneArray.length) {
				phoneSb.append(i + 1).append("-").append(phoneArray[i]).append("-").append(phoneArray[i]);
			} else {
				phoneSb.append(i + 1).append("-").append(phoneArray[i]).append("-").append(phoneArray[i]).append("|");
			}
		}

		len = phoneSb.length();
		sb.append(change(len + "", 10, 16)).append("*").append(phoneSb).append("]");

		uploadReply = sb.toString();

		System.out.println(uploadReply);
	}
}
